package com.bawei.libs_base.mvvm

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.bawei.libs_base.entity.Res
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import okhttp3.Dispatcher

open class BaseViewModel: ViewModel() {
    fun <T> httpRequest(s:suspend ()-> Res<T>, success:(Res<T>)->Unit){
        viewModelScope.launch(Dispatchers.IO) {
            try {
                val res = s.invoke()
                if (res.code == 200) {
                    success(res)
                } else {
                    Log.i( "lr", res.message)
                }
            }catch (e:Exception){
                Log.i( "lr",e.message.toString())
            }
        }
    }

    fun <T> httpRequest(s:suspend ()-> Res<T>, success:(T)->Unit, error:(String)->Unit){
        viewModelScope.launch {
            try {
                val res = s.invoke()
                if (res.code == 200) {
                    success(res.data)
                }else{
                     error(res.message)
                }
            }catch (e:Exception){
                error(e.message.toString())
            }
        }
    }
}
